package com.beg.cant.controller;

import com.beg.cant.comment.result.Result;
import com.beg.cant.comment.utils.WechatSecurityHelper;
import com.beg.cant.dto.PageRequest;
import com.beg.cant.dto.PageResponse;
import com.beg.cant.entity.User;
import com.beg.cant.service.UserService;
import com.beg.cant.vo.UserVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.lang.Long;
import java.util.List;

@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
@Tag(name = "用户管理", description = "用户的增删改查接口")
public class UserController {
    private final UserService userService;
    @Autowired
    private WechatSecurityHelper wechatSecurityHelper;
    @PostMapping
    @Operation(summary = "创建用户", description = "创建一个新的用户")
    public Result<User> createUser(@RequestBody String code) {
        User user = userService.wxLogin(code);
        return Result.success(user);
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取用户", description = "根据ID获取用户信息")
    public Result<UserVO> getUser(@Parameter(description = "用户ID") @PathVariable Long id) {
        return Result.success(userService.getUserById(id));
    }

    @PostMapping("/update")
    @Operation(summary = "更新用户", description = "根据ID更新用户信息")
    public Result<String> updateUser(@RequestBody User user) throws IOException {
        wechatSecurityHelper.checkContent(user.getName(),user.getOpenid());
        userService.updateById(user);
        return Result.success("更新成功");
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除用户", description = "根据ID删除用户")
    public Result<String> deleteUser(@Parameter(description = "用户ID") @PathVariable Long id) {
        userService.removeById(id);
        return Result.success("用户"+id+"删除成功");
    }
    
    @GetMapping("/list")
    @Operation(summary = "获取所有用户", description = "分页获取所有用户的列表")
    public Result<PageResponse<UserVO>> getAllUsers(PageRequest pageRequest) {
        return Result.success(userService.getUserList(pageRequest));
    }

    @GetMapping("/top/balance")
    @Operation(summary = "获取余额最高的前五名用户", description = "按余额降序排序，返回前5名用户信息")
    public Result<List<UserVO>> getTopBalanceUsers() {
        return Result.success(userService.getTopBalanceUsers());
    }
}
